﻿using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Text;

namespace Fin.Interface
{
	public class MyDataContext : IDataContext
	{
		private SQLiteConnection _sQLiteConnection;

		private SQLiteCommand _sQLiteCommand;

		public MyDataContext()
		{
			_sQLiteConnection = new SQLiteConnection(@" Data Source= data\fin.db");
			_sQLiteConnection.Open();
			_sQLiteCommand = new SQLiteCommand(_sQLiteConnection);

		}

		~MyDataContext() {
			_sQLiteConnection.Close();

		}
		

		public bool CopyNew(Config item)
		{
			throw new NotImplementedException();
		}

		public bool Create(string name, bool ifExistsBackAndRemove, Config item)
		{
			throw new NotImplementedException();
		}

		public bool Delete(string name, bool back)
		{
			throw new NotImplementedException();
		}

		private List<ConfigKey> GetConfigKeys() {

			 

			var re = new List<ConfigKey>();
			_sQLiteCommand.Reset();

			_sQLiteCommand.CommandText = "select * from ConfigKeys  ";

			var reader = _sQLiteCommand.ExecuteReader();
			while (reader.Read())
			{
				re.Add(new ConfigKey
				{
					  
					Key = reader["KeyWrod"] + "",
					Type = reader["Orientation"] + "",
					Num = int.Parse(reader["Num"] + "")

				});


			}

			 

			return re;
		}

		private List<Config> GetConfigs() {

			 

			var re = new List<Config>();

			var keys = GetConfigKeys();

			_sQLiteCommand.Reset();
			 
			_sQLiteCommand.CommandText = "select * from Configs ;";

			var reader = _sQLiteCommand.ExecuteReader();
			while (reader.Read())
			{
				var id = int.Parse(reader["Id"] + "");
				var tempKeys = keys.FindAll(  delegate (ConfigKey configKey) {

					return configKey.ConfigId == id;
				});
				re.Add(new Config
				{
					 Keys= tempKeys,
					FileExtension = reader["FileExtension"] + "",
					Name = reader["Name"] + "",
					Sort = int.Parse(reader["Sort"] + "")  

				});


			}

			 

			return re;
		}


		public ConfigRoot GetConfig(bool isConfig = false)
		{
			var configRoot = new ConfigRoot();

			configRoot.TypeList = this.GetConfigs();

			configRoot.Title = "我的工具";

			return configRoot;
		}

		public List<ConfigKey> GetKeyItemsByName(string name)
		{
			var temp=   GetConfigs().Find(delegate(Config config) {

				return config.Name== name;
			});
			var id = temp != null ?  temp.Id:0;

			if (id == 0)
				return null;

		   var tempKeys = GetConfigKeys().FindAll(delegate (ConfigKey configKey) {

				return configKey.ConfigId == id;
			});

			return tempKeys;
		}

		public Config GetTypeListItemByName(string name)
		{
			var temp = GetConfigs().Find(delegate (Config config) {

				return config.Name == name;
			});

			return temp; 
		}
	}
}
